#include "socket.h"
#include <iostream>


Socket::Socket(QObject *parent) : QObject(parent)
{
    sockPtr = new QTcpSocket(parent);
    isDataHead = true;
}

Socket::~Socket()
{
    delete sockPtr;
}

bool Socket::ConnectServer(const QString & addr, quint16 port)
{
    sockPtr->connectToHost(addr, port);
    connect(sockPtr, SIGNAL(readyRead()), this, SLOT(prepareData()));
}

bool Socket::DisConnectServer()
{
    sockPtr->close();

    return true;
}

void Socket::RecvData(Data::DataPtr &dat)
{
    memcpy(dat->GetPictureDataPtr(), data, data_size);
    dat->setValidDataSize(data_size);
}

int Socket::SendData(Data::DataPtr &data)
{
    return sockPtr->write(data->GetSendDataPtr(),
                          data->GetSendDataSize());
}

void Socket::prepareData()
{
    if(isDataHead)
    {
        sockPtr->read((char*)(&data_size),4);
        isDataHead = false;
    }

    int tmp = sockPtr->read((char*)(data + currPtr), data_size - currPtr);
//    std::cout << tmp << " ? " << data_size << std::endl;
    currPtr += tmp;
    if (currPtr == data_size)
    {
        currPtr = 0;
        isDataHead = true;
        emit dataReady();
    }
}



